package com.rad.net.protocol.android.decoder;

import java.util.HashMap;
import java.util.Locale;

import android.text.TextUtils;

import com.rad.net.protocol.android.utils.LogUtils;
import com.rad.net.protocol.common.result.BaseResult;


/** 
 * 类说明：   使用该Json解码器需要将期望的结果类传入，以便解码成相应的结果
 * @author  xinhui.cheng
 * @date    2014-8-20
 * @version 1.0
 */
public class TargetJsonDecoder extends BaseJsonDecoder {

	private static final String TAG = TargetJsonDecoder.class.getSimpleName();
	
	private HashMap<String , Class<? extends BaseResult>> mClassMap;
	
	public TargetJsonDecoder(Class<? extends BaseResult>... expectClasses){
		if(expectClasses != null){
			mClassMap = new HashMap<String, Class<? extends BaseResult>>();
			for (int i = 0; i < expectClasses.length; i++) {
				mClassMap.put(expectClasses[i].getSimpleName().toLowerCase(Locale.US), expectClasses[i]);
			}
		}
	}
	
	@Override
	public Class<? extends BaseResult> getTargetClass(String jsonString) {
		if(TextUtils.isEmpty(jsonString)){
			return null;
		}
		Class<? extends BaseResult> c = null;
		try {
			BaseResult result = decodeJson(jsonString, BaseResult.class);
			if(result == null){
				return null;
			}
			if(mClassMap == null || mClassMap.size() == 0){
				LogUtils.e(TAG, "expect class is null!");
				return null;
			}
			c = mClassMap.get(result.getType().toLowerCase(Locale.US));
			if(c == null){
				LogUtils.e(TAG, "no find taget class ! type"+result.getType());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c;
	}

}
